/*
 * @Description: 
 * @Author: hrc
 * @Date: 2024-12-17 15:51:24
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-02-12 23:49:00
 */
import { ref } from 'vue'

export function useVideoCapture(file) {
  const currentFile = ref()
  const videoInfo = ref({})

  /**
   * @description: 捕获视频帧
   * @param {*} file 视频文件
   * @param {*} time 捕获时间
   * @return {*} 当前帧生成的图片url,当前帧生成的图片blob
   */
  const captureFrame = (file, time) => {
    return new Promise((resolve) => {
      const vdo = document.createElement('video')
      vdo.currentTime = time
      // 下面两行不设一般也没问题，因为点击上传时，用户已经和网页有了交互
      vdo.muted = true //静音
      vdo.autoplay = true //自动播放
      vdo.src = URL.createObjectURL(file) // 不用base64是因为太长了，特别是视频
      vdo.oncanplay = () => {
        const cvs = document.createElement('canvas')
        cvs.width = vdo.videoWidth,
        cvs.height = vdo.videoHeight
        const ctx = cvs.getContext('2d')
        ctx.drawImage(vdo, 0, 0, cvs.width, cvs.height)
        cvs.toBlob(blob => {
          const url = URL.createObjectURL(blob)
          resolve({
            url, //当前帧生成的图片url,
            blob //当前帧生成的图片blob
          })
        })
      }
    })
  }

  /**
   * @description: 获取视频信息
   * @param {*} file 视频文件
   * @return {*} 视频信息
   */
  const getVideoInfo = (file) => {
    return new Promise((resolve) => {
      const vdo = document.createElement('video')
      vdo.muted = true //静音
      vdo.autoplay = true //自动播放
      vdo.src = URL.createObjectURL(file) // 不用base64是因为太长了，特别是视频
      vdo.oncanplay = () => {
        resolve({
          duration: vdo.duration, //总时长
          width: vdo.videoWidth,
          height: vdo.videoHeight
        })
      }
    })
  }

  /**
   * @description: 按视频时长和次数分割视频
   * @param {*} file 视频文件
   * @param {*} num 分隔次数
   * @return {*} 图片信息数组
   */
  const getVideoFrames = async (file, num = 5) => {
    try {
      if (!num || !(num - 1)) return
      const { duration, width, height } = await getVideoInfo(file)
      videoInfo.value.video_duration = duration
      videoInfo.value.video_width = width
      videoInfo.value.video_height = height
      const space = duration / (num - 1)
      const imgArr = []
      for (let index = 0; index < duration; index += space) {
        const { url } = await captureFrame(file, index)
        imgArr.push({
          url,
          key: index
        })
      }
      // 确保最后一个帧被添加
      if (imgArr.length < num) {
        const { url } = await captureFrame(file, duration)
        imgArr.push({
          url,
          key: duration
        })
      }
      return Promise.resolve(imgArr)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  return {
    currentFile,
    captureFrame,
    getVideoInfo,
    getVideoFrames,
    videoInfo
  }
}